<?php session_start() ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Admin</title>
</head>
<body>
	
<?php
require_once 'header.php';
require 'connect.php';

$status = '';
?>


<!-- This will take all city names, login names from current DB and add them to 
 search list tags in html via PHP. After that, depending on selected city, related suburbs are going to be put from DB inside drop check list. Admin will only be able to choose from actual DB data.
 This prevents typos and unneccessery search requests. -->


<div id="search-wrapper">
<div>
    <h1>Admin Area</h1>
</div>
	<div id="search-form" class='container'>
		<div class="row">
					<div id="card-header">
						<h1 id="form-se-head">PROPERTIES AND USERS SEARCH</h1>
					</div>
					<div class="card-body">
						<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
							<div class="form-row">
								<div class="form-group col">
									<select class="form-control" id="city" name="city">
										<option>SELECT CITY</option>
										<!-- adding all distinct cities from DB to search list -->
										<?php 
										$result = mysqli_query($conn,"SELECT DISTINCT city from addresses ORDER BY city ASC");
										if ($result->num_rows > 0){
											while($property_data = mysqli_fetch_array($result)){ 
										?>
										<option value="<?php echo $property_data['city'];?>"><?php echo $property_data['city'];?></option>
										<?php
											}
										} else {$query_error = 'some error getting city data';}
										?>
									</select>
								</div>

								<div class="col">
									<!-- this dropdown populates from first one with 
											help of AJAX script above divs and suburb_list.php -->
									<div class="dropdown input-group">
									<button class="btn btn-secondary dropdown-toggle btn-block" type="button" 
									data-toggle="dropdown">
									SELECT SUBURB
									</button>
									<div class="dropdown-menu">
									<button class="dropdown-item" type="button" id="suburb">
									<option>please select city first</option>
									</button>
									</div>
									</div>
								</div>	

							</div>
							<div class=" form-row">
								<div class=" col">
									<select class="form-control" name='price'>
										<option>Price</option>
										<option value="150000">$150K+</option>
										<option value="300000">$300K+</option>
										<option value="600000">$600K+</option>
										<option value="1000000">$1M+</option>
									</select>
								</div>
								<div class=" col">
									<select class="form-control" name='bedrooms'>
										<option>Bedrooms</option>
										<option value="0">Any</option>
										<option value="1">1+</option>
										<option value="2">2+</option>
										<option value="3">3+</option>
									</select>
								</div>
							</div>
							<br>
							
							<div class="col">

									<!-- <this dropdown shows all users -->
									<div class="dropdown input-group">
									<button class="btn btn-secondary dropdown-toggle btn-block" type="button" 
									data-toggle="dropdown">
									SELECT USERS
									</button>

									<div class="dropdown-menu">
										<!-- adding all distinct USERs from DB to search list -->
										<?php 
										$result = mysqli_query($conn,"SELECT login from users");
										if ($result->num_rows > 0){
											while($user_data = mysqli_fetch_array($result)){ 
										?>
									<button class="dropdown-item" type="button" id="users">
									<input type="checkbox" name="users[]" value="<?php echo $user_data['login'];?>"><?php echo ' '.$user_data['login'];?>
									</button>
									<?php
											}
										} else {$query_error = 'some error getting user data';}
										?>
									</div>
									</div>
							</div>

							<div class="form-group text-center">
									<input id="sub-btn-search" type="submit" name="submit" class="btn-max btn-size" value="Submit" id="submit_search">
							</div>
						</form>
					</div>
		</div>
	</div>
</div>

<div class="search-results">

<?php

// After submit every form variable from $_POST array is checked for existence, added to SQL statement and searched in DB.
// Then results are printed in cards with buttons. From cards admin can delete properties, tag and untag them as "featured" so they can be displayed in home page.

if( isset($_POST['submit'])){

    $current_user = $_SESSION['user_id'];

// SQL statement below initially empty. Form variables are added to statement one by one in section below
	$sql = "";

	if( $_POST['city'] !== "SELECT CITY"){

		$city = $_POST['city'];

		$sql = "SELECT bedrooms, price, description, suburb, city, street_name, street_number,  properties.id, users.login, properties.date_listed FROM properties
		INNER JOIN addresses ON addresses.property_id = properties.id
        INNER JOIN users ON users.id = properties.user_id
		WHERE city = '".$city."'";

		if( !empty($_POST['suburbs'])){

			$suburbs_names = "";

			foreach($_POST['suburbs'] as $value){

				if (empty($suburbs_names)){

					$suburbs_names = "'".$value."'"; 
				}
				else{ $suburbs_names = $suburbs_names.", '$value'"; }
        }

        $sql = "SELECT bedrooms, price, description, suburb, city, street_name, street_number, properties.id, users.login, properties.date_listed FROM properties 
					INNER JOIN addresses ON addresses.property_id = properties.id
                    INNER JOIN users ON users.id = properties.user_id
					WHERE addresses.suburb IN (".$suburbs_names.")";

		}
	} else { $status = "City has to be selected."; }
													
	if( !empty($_POST['users'])){

		$users_logins = "";

        foreach($_POST['users'] as $value){

            if (empty($users_logins)){   

                $users_logins = "'".$value."'"; 
            }
            else{ $users_logins = $users_logins.", '.$value.'"; }
        }
					
        if (empty($sql)){

	        $sql = "SELECT bedrooms, price, description, suburb, city, street_name, street_number,  properties.id, users.login, properties.date_listed FROM properties
			INNER JOIN users ON users.id = properties.user_id
	        INNER JOIN addresses ON addresses.property_id = properties.id
			WHERE users.login IN (".$users_logins.")";
		}
		else 
		    {
	            $sql = $sql." AND users.login IN (".$users_logins.")";

	            echo $sql."  second SQL!!!!";
	        }
		}

	if($_POST['price'] !== 'Price'){

		$price = $_POST['price'];

		if(empty($sql)){
			$sql = "SELECT bedrooms, price, description, suburb, city, street_name, street_number,  properties.id, users.login, properties.date_listed FROM properties
				INNER JOIN users ON users.id = properties.user_id
		        INNER JOIN addresses ON addresses.property_id = properties.id
				WHERE properties.price >  ".$price;

				// echo $sql;

		}else { $sql = $sql." AND price > ".$price; }
		
	}


	if ($_POST['bedrooms'] !== 'Bedrooms'){

		$bedrooms = $_POST['bedrooms'];
		if(empty($sql)){
			$sql = "SELECT bedrooms, price, description, suburb, city, street_name, street_number,  properties.id, users.login, properties.date_listed FROM properties
				INNER JOIN users ON users.id = properties.user_id
		        INNER JOIN addresses ON addresses.property_id = properties.id
				WHERE properties.bedrooms >  ".$bedrooms;

		} else { $sql = $sql." AND bedrooms > ".$bedrooms;}
	}

		$result = mysqli_query($conn, $sql);

		if (mysqli_num_rows($result) > 0){
			while($property_data = mysqli_fetch_assoc($result)){
				
				//getting photos urls or current property

				$sql = "SELECT property_id FROM featuredlists WHERE property_id = $property_data[id]";
				$result_featured_list = mysqli_query($conn, $sql);

				if (mysqli_num_rows($result_featured_list) ==  0 ) {
					$featured_list_state = "Tag as Featured";
					$btn_color = "add-to-wishlist-btn";
				}
				else {
					$featured_list_state = "Remove from Featured";
					$btn_color = "add-to-wishlist-btn-toggle add-to-wishlist-btn";
				}

				$sql = "SELECT photo_url FROM photos WHERE property_id = $property_data[id]";
				$result_photos = mysqli_query($conn, $sql);

				if (mysqli_num_rows($result_photos) > 0){ ?>

					<div>
						<?php $current_property_photo_urls = mysqli_fetch_assoc($result_photos);
						//echo ($current_property_photo_urls['photo_url']);////displaying for debuging purposes only
						$photoUrl = './'.$current_property_photo_urls['photo_url'];
						?>
					</div>
                    <section class="search-results-body">
                        <div class="column one-half">
                            <div class="col-group dis-card">
                                <div class="img-container">
                                    <img src="<?php echo $photoUrl;?>" class="house-img" width="300px" height="200px">
                                </div>
                                <h2 class="house-title"><?php echo $property_data['street_number']. ' '.$property_data['street_name']. ', '.$property_data['suburb']. ', '.$property_data['city']  ?></h2>
                                    <div class="bedroom-wrapper">
                                        <span class="house-price"><?php echo '$'.number_format($property_data['price']); ?></span>
                                        <div class="bed-wrapper">
                                            <span class="bed-number"><?php echo $property_data['bedrooms'] ?></span>
                                            <img src="WebsiteImg/bed.png" class="bed-img">
                                        </div>
                                    </div>
                                    <p class="desc-text-card-admin"><?php echo $property_data['description'] ?></p>
                                    <p class="prop-details-text date-created">Date Listed: <?php echo $property_data['date_listed']?></p>
                                    <p class="prop-details-text user-name">User Name: <?php echo $property_data['login']?></p>
                                    <a class="<?php echo $btn_color;?> " onclick="AddFeatured(<?php echo $property_data['id']; ?>)" data="<?php echo $property_data['id']; ?>"><?php echo $featured_list_state;?></a>
                                    <a href="admin_edit.php?edit=<?php echo $property_data['id']; ?>" id="<?php echo "e".$property_data['id']; ?>" class="add-to-wishlist-btn " type="submit" class="btn btn-primary">Edit Property</a>
                                    <a class="remove-prop-btn " onclick="deleteP(<?php echo $property_data['id']; ?>)" id="<?php echo $property_data['id']; ?>">Delete Property</a>
                            </div>
                        </div>
                    </section>

			<?php
				}
			}
	} 
}

?>


<!-- this AJAX script is takes value from "select city" field, sends it to suburb_list.php and displays return -->

<script type="text/javascript">
   $(document).ready(function(){
   	$("#city").on("change",function(){
   	var city_selected = this.value;
    $.ajax({
		url: "suburb_list.php",
		type: "POST",
		cache:false,
		data:{ city_selected: city_selected },
  		success:function(result){
      	$("#suburb").html(result);
  		}
    });	
  });
});
</script>


<!-- here ajax reacts on 'add/ remove from featured' button. sends request to 'addtofeatured.php' and get back 'true/ false' return. after changes button styles and text accordingly -->

<script type="text/javascript">
function AddFeatured(data){
	var link_data = data;
	   // console.log('Link_data:'+link_data);
       $.ajax({
          type: "POST",
          url: 'addtofeatured.php',
          cache:false,
          data: { link_data: link_data },
          	success:function(result){
				  // console.log("AJ success"+result);
               if(result == 1)
               {
                   $('a[data="' + link_data + '"]').addClass("add-to-wishlist-btn-toggle").text("Remove from Featured");
               }
               else{
                   $('a[data="' + link_data + '"]').removeClass("add-to-wishlist-btn-toggle").text("Tag as Featured");
               }
          },
		  error:function(result){
			console.log("AJ error");
		  }
       });   
}
</script>

<!-- this AJAX reacts to "delete this property" button click. calls 'delete-property.php' takes true/false return and changes card field accordingly -->

<script type="text/javascript">
function deleteP(id){
	var delete_p_id = id;
	   // console.log('delete_p_id:'+delete_p_id);
       $.ajax({
          type: "POST",
          url: 'delete-property.php',
          cache:false,
          data: { delete_p_id: delete_p_id },
          	success:function(result_delete){
				  // console.log("AJ delete success "+result_delete);
                  if(result_delete == 1)
               {
                   // console.log ("deleted-changed-txt");
                   $('a[id="' + delete_p_id + '"]').addClass("removed-property-btn removed-property-btn-wrapper").removeClass("remove-prop-btn").text("Property Deleted");
                   $('a[data="' + delete_p_id + '"]').addClass("dis-none");
                   $('a[id="'+ "e" + delete_p_id + '"]').addClass("dis-none");

               }
               else{
                    // console.log ("deleted-unchanged-txt");
                   $('a[id="' + delete_p_id + '"]').removeClass("add-to-wishlist-btn-toggle");
               }
          },
		  error:function(result_delete){
			console.log("AJ delete error");
		  }
       });   
    }
</script>



</div>

</body>
</html>